// 获取DOM元素
const cityInput = document.getElementById('cityInput');
const queryButton = document.getElementById('queryButton');
const weatherResult = document.getElementById('weatherResult');
const historyButton = document.getElementById('historyButton');
const historyDropdown = document.getElementById('historyDropdown');
const clearHistory = document.getElementById('clearHistory');
const historyList = document.getElementById('historyList');
const modalOverlay = document.getElementById('modalOverlay');
let isHistoryVisible = false;

// 添加回车键触发查询
cityInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        handleWeatherQuery();
    }
});

queryButton.addEventListener('click', handleWeatherQuery);

function handleWeatherQuery() {
    const city = cityInput.value.trim();
    if (city === '') {
        showNotification('请输入城市名称');
        return;
    }
    fetchWeather(city);
}

function showNotification(message) {
    weatherResult.innerHTML = `
        <div style="color: #666; text-align: center;">
            <i class="fas fa-info-circle"></i> ${message}
        </div>
    `;
}

// 添加城市数据
const cityData = {
    // 直辖市
    '北京': 'Beijing',
    '上海': 'Shanghai',
    '天津': 'Tianjin',
    '重庆': 'Chongqing',
    
    // 华北地区
    '石家庄': 'Shijiazhuang',
    '太原': 'Taiyuan',
    '呼和浩特': 'Hohhot',
    
    // 东北地区
    '沈阳': 'Shenyang',
    '大连': 'Dalian',
    '长春': 'Changchun',
    '哈尔滨': 'Harbin',
    
    // 华东地区
    '南京': 'Nanjing',
    '苏州': 'Suzhou',
    '无锡': 'Wuxi',
    '杭州': 'Hangzhou',
    '宁波': 'Ningbo',
    '温州': 'Wenzhou',
    '合肥': 'Hefei',
    '福州': 'Fuzhou',
    '厦门': 'Xiamen',
    '南昌': 'Nanchang',
    '济南': 'Jinan',
    '青岛': 'Qingdao',
    
    // 华中地区
    '郑州': 'Zhengzhou',
    '武汉': 'Wuhan',
    '长沙': 'Changsha',
    
    // 华南地区
    '广州': 'Guangzhou',
    '深圳': 'Shenzhen',
    '珠海': 'Zhuhai',
    '佛山': 'Foshan',
    '南宁': 'Nanning',
    '海口': 'Haikou',
    
    // 西南地区
    '成都': 'Chengdu',
    '贵阳': 'Guiyang',
    '昆明': 'Kunming',
    '拉萨': 'Lhasa',
    
    // 西北地区
    '西安': 'Xi\'an',
    '兰州': 'Lanzhou',
    '西宁': 'Xining',
    '银川': 'Yinchuan',
    '乌鲁木齐': 'Urumqi',
    
    // 其他重要城市
    '常州': 'Changzhou',
    '南通': 'Nantong',
    '扬州': 'Yangzhou',
    '徐州': 'Xuzhou',
    '嘉兴': 'Jiaxing',
    '金华': 'Jinhua',
    '绍兴': 'Shaoxing',
    '台州': 'Taizhou',
    '烟台': 'Yantai',
    '威海': 'Weihai',
    '潍坊': 'Weifang',
    '临沂': 'Linyi',
    '洛阳': 'Luoyang',
    '开封': 'Kaifeng',
    '株洲': 'Zhuzhou',
    '湘潭': 'Xiangtan',
    '衡阳': 'Hengyang',
    '东莞': 'Dongguan',
    '中山': 'Zhongshan',
    '惠州': 'Huizhou',
    '江门': 'Jiangmen',
    '汕头': 'Shantou',
    '泉州': 'Quanzhou',
    '三亚': 'Sanya',
    '遵义': 'Zunyi',
    '绵阳': 'Mianyang',
    '宝鸡': 'Baoji',
    '咸阳': 'Xianyang',
    '大同': 'Datong',
    '包头': 'Baotou',
    '鞍山': 'Anshan',
    '抚顺': 'Fushun',
    '吉林': 'Jilin',
    '齐齐哈尔': 'Qiqihar'
};

// 扩充城市图片数据
const cityImages = {
    '北京': 'https://images.unsplash.com/photo-1600454021970-351eff4a6554',
    '上海': 'https://images.unsplash.com/photo-1548919973-5cef591cdbc9',
    '广州': 'https://images.unsplash.com/photo-1583491470869-ca0e85bd3c5b',
    '深圳': 'https://images.unsplash.com/photo-1545893835-abaa50cbe628',
    '杭州': 'https://images.unsplash.com/photo-1598987644155-5c4e3f5b7b22',
    '成都': 'https://images.unsplash.com/photo-1545586598-8142f7854f2a',
    '武汉': 'https://images.unsplash.com/photo-1590237580429-2577d0e2b029',
    '西安': 'https://images.unsplash.com/photo-1626698358073-8a21b1529e81',
    '重庆': 'https://images.unsplash.com/photo-1564477914688-4c9940533e75',
    '南京': 'https://images.unsplash.com/photo-1568880905967-a711f4359472',
    '天津': 'https://images.unsplash.com/photo-1617862244237-c96bb1caabe4',
    '厦门': 'https://images.unsplash.com/photo-1618824834718-92f8469a4dd1',
    '青岛': 'https://images.unsplash.com/photo-1567521463850-4939134bcd4a',
    '大连': 'https://images.unsplash.com/photo-1621170834987-0dce9c3dc35e'
};

// 添加默认背景图片
const defaultCityImage = 'https://images.unsplash.com/photo-1534088568595-a066f410bcda';

// 修改 setCityBackground 函数
async function setCityBackground(city) {
    const imageUrl = cityImages[city];
    const overlay = document.getElementById('backgroundOverlay');
    
    // 添加渐变过渡效果
    overlay.style.opacity = '0';
    
    if (!imageUrl) {
        // 如果没有找到对应的城市图片，使用护眼色背景
        overlay.style.cssText = `
            background: #E3EDCD;
            opacity: 1;
            transition: opacity 1s ease;
        `;
        return;
    }
    
    // 预加载图片
    const img = new Image();
    img.src = imageUrl;
    
    img.onload = () => {
        overlay.style.cssText = `
            background-image: linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url('${imageUrl}');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            opacity: 1;
            transition: opacity 1s ease;
        `;
    };
    
    img.onerror = () => {
        // 图片加载失败时也使用护眼色背景
        overlay.style.cssText = `
            background: #E3EDCD;
            opacity: 1;
            transition: opacity 1s ease;
        `;
    };
}

// 修改 fetchWeather 函数
function fetchWeather(city) {
    // 保存查询历史
    const history = JSON.parse(localStorage.getItem('weatherHistory') || '[]');
    const newRecord = {
        city: city,
        time: new Date().getTime()
    };
    
    // 移除可能存在的相同城市记录
    const filteredHistory = history.filter(item => item.city !== city);
    
    // 添加新记录到开头
    filteredHistory.unshift(newRecord);
    
    // 只保留最近10条记录
    if (filteredHistory.length > 10) {
        filteredHistory.pop();
    }
    
    localStorage.setItem('weatherHistory', JSON.stringify(filteredHistory));

    const apiKey = '114122abe5b34462efb8a11dfbf188a5';
    // 如果输入的是中文，转换为英文
    const searchCity = cityData[city] || city;
    const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(searchCity)}&appid=${apiKey}&units=metric&lang=zh_cn`;

    showNotification('<i class="fas fa-spinner fa-spin"></i> 正在查询天气，请稍候...');

    fetch(apiUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error(response.status === 404 ? '未找到该城市' : '服务暂时不可用');
            }
            return response.json();
        })
        .then(data => {
            if (data.cod === 200) {
                // 显示中文城市名
                const displayCity = Object.keys(cityData).find(key => cityData[key].toLowerCase() === city.toLowerCase()) || city;
                displayWeatherData(displayCity, data);
            }
        })
        .catch(error => {
            showNotification(`<i class="fas fa-exclamation-circle"></i> ${error.message}`);
        });
}

// 修改输入建议功能
cityInput.addEventListener('input', function() {
    const value = this.value.trim().toLowerCase();
    if (value) {
        // 同时搜索中文名和英文名
        const matches = Object.entries(cityData).filter(([cn, en]) => 
            cn.toLowerCase().includes(value) || 
            en.toLowerCase().includes(value)
        );

        if (matches.length) {
            suggestionsDiv.innerHTML = matches.map(([cn, en]) => `
                <div class="suggestion-item" style="padding: 10px 15px; cursor: pointer; transition: all 0.2s ease;">
                    <span style="color: #1e3c72; font-weight: 500;">${cn}</span>
                    <span style="color: #666; font-size: 0.9em; margin-left: 8px;">${en}</span>
                </div>
            `).join('');
            
            suggestionsDiv.style.display = 'block';
            
            document.querySelectorAll('.suggestion-item').forEach(item => {
                item.addEventListener('mouseover', () => {
                    item.style.backgroundColor = '#f0f4f8';
                });
                item.addEventListener('mouseout', () => {
                    item.style.backgroundColor = 'white';
                });
                item.addEventListener('click', () => {
                    // 获取中文城市名
                    const cityName = item.querySelector('span').textContent;
                    cityInput.value = cityName;
                    suggestionsDiv.style.display = 'none';
                    handleWeatherQuery();
                });
            });
        } else {
            // 如果没有匹配的建议城市，保持输入的值
            suggestionsDiv.style.display = 'none';
        }
    } else {
        // 当输入框为空时，显示所有城市
        const allCities = Object.entries(cityData).map(([cn, en]) => `
            <div class="suggestion-item" style="padding: 10px 15px; cursor: pointer; transition: all 0.2s ease;">
                <span style="color: #1e3c72; font-weight: 500;">${cn}</span>
                <span style="color: #666; font-size: 0.9em; margin-left: 8px;">${en}</span>
            </div>
        `).join('');
        
        suggestionsDiv.innerHTML = allCities;
        suggestionsDiv.style.display = 'block';
    }
});

// 添加输入框获得焦点时显示所有城市的功能
cityInput.addEventListener('focus', function() {
    if (this.value.trim() === '') {
        const allCities = Object.entries(cityData).map(([cn, en]) => `
            <div class="suggestion-item" style="padding: 10px 15px; cursor: pointer; transition: all 0.2s ease;">
                <span style="color: #1e3c72; font-weight: 500;">${cn}</span>
                <span style="color: #666; font-size: 0.9em; margin-left: 8px;">${en}</span>
            </div>
        `).join('');
        
        suggestionsDiv.innerHTML = allCities;
        suggestionsDiv.style.display = 'block';
        
        // 为所有建议项添加事件监听器
        document.querySelectorAll('.suggestion-item').forEach(item => {
            item.addEventListener('mouseover', () => {
                item.style.backgroundColor = '#f0f4f8';
            });
            item.addEventListener('mouseout', () => {
                item.style.backgroundColor = 'white';
            });
            item.addEventListener('click', () => {
                const cityName = item.querySelector('span').textContent;
                cityInput.value = cityName;
                suggestionsDiv.style.display = 'none';
                handleWeatherQuery();
            });
        });
    }
});

// 点击外部关闭建议列表
document.addEventListener('click', function(e) {
    if (!e.target.closest('.input-container')) {
        suggestionsDiv.style.display = 'none';
    }
});

// 添加错误提示函数
function showError(message) {
    weatherResult.innerHTML = `
        <div class="error-message" style="
            text-align: center;
            padding: 20px;
            color: #721c24;
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            border-radius: 15px;
            margin-top: 20px;
        ">
            <i class="fas fa-exclamation-circle"></i>
            <p style="margin: 10px 0;">${message}</p>
            <button onclick="handleWeatherQuery()" class="retry-button" style="
                background: #dc3545;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 8px;
                cursor: pointer;
                margin-top: 10px;
            ">重试</button>
        </div>
    `;
}

// 修改天气数据显示函数，添加更多信息
function displayWeatherData(city, data) {
    // 设置城市背景
    setCityBackground(city);
    
    const getWindDirection = (deg) => {
        const directions = ['北', '东北', '东', '东南', '南', '西南', '西', '西北'];
        return directions[Math.round(deg / 45) % 8];
    };

    // 扩展天气图标映射
    const weatherIcons = {
        Clear: 'sun',
        Clouds: 'cloud',
        Rain: 'cloud-rain',
        Snow: 'snowflake',
        Thunderstorm: 'bolt',
        Drizzle: 'cloud-showers-heavy',
        Mist: 'smog',
        Fog: 'fog',
        Haze: 'smog',
        Dust: 'wind',
        Sand: 'wind',
        Ash: 'smog',
        Squall: 'wind',
        Tornado: 'tornado'
    };

    // 获取天气建议
    const getWeatherAdvice = (temp, weather, humidity, windSpeed) => {
        let advice = [];
        
        // 根据温度范围给出建议
        if (temp <= 0) {
            advice.push({
                icon: 'fa-snowflake',
                text: '温度低于0度，注意防寒保暖，建议穿羽绒服等厚重衣物'
            });
        } else if (temp <= 10) {
            advice.push({
                icon: 'fa-temperature-low',
                text: '温度较低，建议穿厚外套、毛衣、棉服等保暖衣物'
            });
        } else if (temp <= 20) {
            advice.push({
                icon: 'fa-temperature-quarter',
                text: '温度舒适，建议穿薄外套或长袖衣物'
            });
        } else if (temp <= 28) {
            advice.push({
                icon: 'fa-temperature-half',
                text: '温度适中，建议穿短袖T恤、衬衫等轻便衣物'
            });
        } else if (temp <= 35) {
            advice.push({
                icon: 'fa-temperature-high',
                text: '温度较高，注意防暑降温，建议穿轻薄透气的衣物'
            });
        } else {
            advice.push({
                icon: 'fa-temperature-full',
                text: '温度过高，避免长时间户外活动，注意补充水分'
            });
        }

        // 根据湿度给出建议
        if (humidity > 80) {
            advice.push({
                icon: 'fa-droplet',
                text: '湿度较大，注意防潮，建议开启除湿设备'
            });
        } else if (humidity < 30) {
            advice.push({
                icon: 'fa-droplet-slash',
                text: '湿度偏低，注意保湿，多补充水分'
            });
        }

        // 根据天气状况给出建议
        if (weather.includes('Rain') || weather.includes('Drizzle')) {
            advice.push({
                icon: 'fa-umbrella',
                text: '降雨天气，记得携带雨具出行'
            });
        } else if (weather.includes('Snow')) {
            advice.push({
                icon: 'fa-snowflake',
                text: '降雪天气，注意防滑，建议穿防水鞋'
            });
        } else if (weather.includes('Clear')) {
            if (temp > 28) {
                advice.push({
                    icon: 'fa-sun',
                    text: '晴天炎热，建议涂抹防晒霜，戴遮阳帽'
                });
            }
        }

        // 根据风速给出建议
        if (windSpeed > 10) {
            advice.push({
                icon: 'fa-wind',
                text: '风力较强，注意防风，外出小心行走'
            });
        } else if (windSpeed > 5) {
            advice.push({
                icon: 'fa-wind',
                text: '有一定风力，建议适当添加衣物'
            });
        }

        return advice;
    };

    const icon = weatherIcons[data.weather[0].main] || 'cloud';
    const temperature = Math.round(data.main.temp);
    const feelsLike = Math.round(data.main.feels_like);
    const windDirection = getWindDirection(data.wind.deg);
    const weatherAdvice = getWeatherAdvice(
        temperature, 
        data.weather[0].main, 
        data.main.humidity, 
        data.wind.speed
    );

    // 修改建议显示部分
    const adviceHTML = weatherAdvice.map(item => `
        <div class="advice-item">
            <i class="fas ${item.icon}"></i>
            ${item.text}
        </div>
    `).join('');

    // 添加空气质量指数显示（如果有数据）
    const getAQILevel = (aqi) => {
        if (aqi <= 50) return '优';
        if (aqi <= 100) return '良';
        if (aqi <= 150) return '轻度污染';
        if (aqi <= 200) return '中度污染';
        if (aqi <= 300) return '重度污染';
        return '严重污染';
    };

    weatherResult.innerHTML = `
        <div class="weather-main">
            <i class="fas fa-${icon} weather-icon"></i>
            <h2 class="city-name">${city}</h2>
            <div class="temperature">${temperature}°C</div>
            <div class="weather-description">${data.weather[0].description}</div>
            
            <div class="weather-advice">
                ${adviceHTML}
            </div>
        </div>

        <div class="weather-info">
            <div class="weather-item">
                <i class="fas fa-temperature-high"></i>
                <span>体感温度</span>
                <div>${feelsLike}°C</div>
            </div>
            <div class="weather-item">
                <i class="fas fa-tint"></i>
                <span>湿度</span>
                <div>${data.main.humidity}%</div>
            </div>
            <div class="weather-item">
                <i class="fas fa-wind"></i>
                <span>风向风速</span>
                <div>${windDirection}风 ${data.wind.speed}m/s</div>
            </div>
            <div class="weather-item">
                <i class="fas fa-compress-arrows-alt"></i>
                <span>气压</span>
                <div>${data.main.pressure}hPa</div>
            </div>
        </div>

        <div class="additional-info">
            <div class="sun-info">
                <div class="sunrise">
                    <i class="fas fa-sunrise"></i>
                    <span>日出</span>
                    <div>${new Date(data.sys.sunrise * 1000).toLocaleTimeString('zh-CN', {
                        hour: '2-digit',
                        minute: '2-digit'
                    })}</div>
                </div>
                <div class="sunset">
                    <i class="fas fa-sunset"></i>
                    <span>日落</span>
                    <div>${new Date(data.sys.sunset * 1000).toLocaleTimeString('zh-CN', {
                        hour: '2-digit',
                        minute: '2-digit'
                    })}</div>
                </div>
            </div>
            
            <div class="visibility-info">
                <i class="fas fa-eye"></i>
                <span>能见度</span>
                <div>${(data.visibility / 1000).toFixed(1)}km</div>
            </div>
        </div>
    `;

    // 添加动画效果
    document.querySelectorAll('.weather-item, .advice-item').forEach((item, index) => {
        item.style.opacity = '0';
        item.style.transform = 'translateY(20px)';
        setTimeout(() => {
            item.style.transition = 'all 0.3s ease';
            item.style.opacity = '1';
            item.style.transform = 'translateY(0)';
        }, index * 100);
    });
}

// 添加背景图片加载时的过渡效果
function addBackgroundTransition() {
    const overlay = document.getElementById('backgroundOverlay');
    overlay.style.transition = 'opacity 1s ease';
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
    addBackgroundTransition();
});

// 历史记录按钮点击事件
historyButton.addEventListener('click', (e) => {
    e.stopPropagation();
    isHistoryVisible = !isHistoryVisible;
    historyDropdown.style.display = isHistoryVisible ? 'block' : 'none';
    modalOverlay.style.display = isHistoryVisible ? 'block' : 'none';
    historyButton.classList.toggle('active', isHistoryVisible);
    if (isHistoryVisible) {
        updateHistoryList();
        historyDropdown.style.animation = 'none';
        historyDropdown.offsetHeight;
        historyDropdown.style.animation = 'slideDown 0.3s ease';
    }
});

// 点击其他地方关闭历史记录
document.addEventListener('click', (e) => {
    if (!historyDropdown.contains(e.target) && !historyButton.contains(e.target)) {
        historyDropdown.style.display = 'none';
        modalOverlay.style.display = 'none';
        isHistoryVisible = false;
        historyButton.classList.remove('active');
    }
});

// 清除历史记录
clearHistory.addEventListener('click', (e) => {
    e.stopPropagation();
    if (confirm('确定要清空所有历史记录吗？')) {
        localStorage.removeItem('weatherHistory');
        updateHistoryList();
    }
});

// 更新历史记录列表
function updateHistoryList() {
    const history = JSON.parse(localStorage.getItem('weatherHistory') || '[]');
    if (history.length === 0) {
        historyList.innerHTML = `
            <div class="history-item" style="justify-content: center; color: #666;">
                <i class="fas fa-info-circle"></i>
                <span style="margin-left: 8px;">暂无查询记录</span>
            </div>`;
        return;
    }

    historyList.innerHTML = history.map((item, index) => `
        <div class="history-item" 
             onclick="handleHistoryClick('${item.city}')"
             style="animation: slideDown ${0.1 + index * 0.05}s ease;">
            <span class="city-name">
                <i class="fas fa-map-marker-alt" style="margin-right: 8px; color: #1e3c72;"></i>
                ${item.city}
            </span>
            <span class="query-time">${formatTime(item.time)}</span>
        </div>
    `).join('');
}

// 格式化时间
function formatTime(timestamp) {
    const date = new Date(timestamp);
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    if (date.toDateString() === today.toDateString()) {
        return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else if (date.toDateString() === yesterday.toDateString()) {
        return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else {
        return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    }
}

// 处理历史记录点击
function handleHistoryClick(city) {
    cityInput.value = city;
    handleWeatherQuery();
    historyDropdown.style.display = 'none';
    modalOverlay.style.display = 'none';
    isHistoryVisible = false;
    historyButton.classList.remove('active');
}